package zzzhc.image.recognize.filter;

import zzzhc.image.recognize.Filter;
import zzzhc.image.recognize.RecognizeContext;

public class LineFilter implements Filter {

	private static final long serialVersionUID = -630504720834819526L;

	private int threshold = -1;

	public int getThreshold() {
		return threshold;
	}

	public void setThreshold(int threshold) {
		this.threshold = threshold;
	}

	public void doFilter(RecognizeContext context) {
		int minSize = threshold;
		if (minSize < 0) {
			minSize = context.getWidth() / 4;
		}
		for (int y = 0; y < context.getHeight(); y++) {
			int start = -1;
			int cur = -1;
			for (int x = 0; x < context.getWidth(); x++) {
				int p = context.getValue(x, y);
				if (p == 1) {
					if (start < 0) {
						start = x;
						cur = x;
						continue;
					} else {
						cur = x;
					}
				}
				if (start >= 0 && (p == 0 || x == context.getWidth() - 1)) {
					if (cur - start >= minSize) {
						for (int xx = start; xx <= cur; xx++) {
							int v = context.getValue(xx, y - 1)
									+ context.getValue(xx, y)
									+ context.getValue(xx, y + 1);
							if (v <= 2) {
								context.setValue(xx, y, 0);
							}
						}
					}
				}
				if (p == 0) {
					start = -1;
					cur = -1;
				}
			}
		}
	}
}
